using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace JBORPG.Net
{
    public class Client
    {
        private TcpClient m_Client;
        private IPEndPoint m_EndPoint;
        private NetHandler m_NetHandler;

        public Client(NetHandler nh, IPAddress ipa, Int32 port)
        {
            this.m_NetHandler = nh;
            this.m_EndPoint = new IPEndPoint(ipa, port);

            m_Client = new TcpClient();
        }

        public Client(NetHandler nh, IPEndPoint iep)
        {
            this.m_NetHandler = nh;
            this.m_EndPoint = iep;

            m_Client = new TcpClient();
        }

        public void Connect()
        {
            m_Client.Connect(m_EndPoint);

            if (!m_Client.Connected)
                throw new Exception("Unable to connect");
        }

        public T Invoke<T>(String type, String method, params Object[] parameters)
        {
            return (T)this.Invoke(type, method, parameters).Return;
        }

        public Invoker Invoke(String type, String method, params Object[] parameters)
        {
            Invoker i = m_NetHandler.Invoke(m_Client, type, method, parameters);
            
            //
            // check for exceptions
            if (i.Return.GetType().IsSubclassOf(typeof(Exception)) || i.Return.GetType() == typeof(Exception))
            {
                Exception baseException = (Exception)i.Return;

                while (baseException.InnerException != null)
                {
                    baseException = baseException.InnerException;
                }

                throw baseException;
            }


            return i;
        }
    }
}
